<?php


namespace app\test\controller;


use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use think\Controller;
use think\Db;
use think\Env;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * 占星师平台 敏感信息加密 + 清空缓存
 * Class TestAstrologer
 * @package app\test\controller
 */
class TestAstrologer extends Controller
{
    /**
     * 清空缓存
     * https://local-beta-wechat.goddessxzns.com/test/test_astrologer/test_clean_redis
     */
    private function test_clean_redis()
    {
        $keys_info = [
            [
                'name' => 'astr_admin:astr:info:*',
                'msg' => '占星师缓存',
                'db' => 0
            ],
            [
                'name' => 'astr_admin:astr_info:info:*',
                'msg' => '占星师详细信息缓存',
                'db' => 0
            ]
        ];

        $result = [];//返回信息

        $redis = new \Redis();
        $redis->connect(Env::get('redis.host'), Env::get('redis.port'));
        $redis->auth(Env::get('redis.password'));
        foreach ($keys_info as $k => $v)
        {
            $redis->select($v['db']);
            $deleteKey = $v['name'];
            $keys = $redis->keys($deleteKey);
            $count = $redis->delete($keys);

            $result[$k]['db'] = $v['db'];
            $result[$k]['name'] = $deleteKey;
            $result[$k]['msg'] = $v['msg'];
            $result[$k]['count'] = $count;
        }

        //返回数据
        if ($result && count($result) > 0)
        {
            return show(200, '删除成功！', $result);
        } else
        {
            return show(200, '没有删除任何缓存！');
        }

    }

    /**
     * 加密某条数据
     */
    private function en()
    {
        $str = '交通银行上海青浦支行';
        $en = Util::encryptWithOpenssl($str);
        return show(200, '加密成功', ['original' => $str, 'en' => $en]);
    }


    /**
     * 解密某条数据
     */
    private function decode()
    {
//        id=110有问题
        $str = '7qcVzN2idf/tszpYYrvuu8ViWX4iYZBKq6Tw+B7gfVL1Wvk0t4AM+VnKEK9nL7i4ND0vtDafJgNAxhiEiTTKZERVwAPo58FtGcOkJvoUmo1ZN/HjYF0H2BRNB1uiuf7rtYamPygmDNxkHFGoNmIp/B+4ZkmulZBO03FKmOgMeJ2ohR3I49qw1tndfajfGGWNlMjgDtBlmf2AhQ6FSE0be5YBVdxtIenrCVicebP/M2j66+BuXWaLLuJQnyr3jY4TZn4zCRpj3nDyKv4z+JVM3lgXcTUMbnRVjq+5qWrO8RtIOd6Zvlhj5vPSL/et/LoP4R3P+zfj6qE9/uAGel0vUyTWNQLLFlG8EteUDuSQaHxpP3fKpHhGnHZP1rHAMxUIXUea5gSQMjdftLeTkD/ubuQec9kgih6D5WR2yH6Nzuk=';
//        $str = 'o61stfp/uc5wWWR9sQ8XC1ywgTVgxX4j3K4gMZOZg1ym712v2w006Qh3H/Mr0NuE0N8wPWQBtZdT+lKwf1Hxp1cczJMNV4xdn3Qun2GaNM6qxen8YJ0JGHdccRWREvaiHgZfyusGxwa77qT4s1jB+7oV6lm5HC9aSbyFha/966MtvP1a1lMcOU/3OLAYkxVxaMP69CZ3xgvny0t1euJ5kRkN69wUBcMoXSYHnFq/M81mMDuIycLyw8CXpONf9tJu3zIwevR00m6SwHc7+2JJkJSBw79S7m4IguWIfNns/oO3P9IMYQctNoZfSYWtu6kxa2eUPBhFxEIbe+/wtQyPgzsGyV0xBHUDW+lXWVAIfoM4PW85gM1YjwvH4NnlCZQvdP7v6KCk1/zjKg9oKRjUFCTvGvnOnoIMwJuw8s+QBVKWeRquxh8AdJZkaW2Ny8EXTs6P80x9XmGxxDU9DKE28g==';
        $en = Util::decryptWithOpenssl($str);
        $en = json_decode($en, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        return show(200, '解密成功', ['original' => $str, 'en' => $en]);
    }


    /**
     * 把银行卡、身份证数据加密，只能执行一次
     * https://local-beta-wechat.goddessxzns.com/test/test_astrologer/test
     */
    private function test()
    {
        //需要加密的key
        $keys_encode = ['name', 'telphone', 'id_card', 'left_pic_info', 'right_pic_info', 'bank_card', 'bank_name', 'bank_branch_name', 'bank_id_card', 'bank_id_card_name', 'bank_info', 'bank_branch_info'];
        try
        {
            $list = Db::table('zlcr_astr_info')->select();
            $list = json_decode(json_encode($list, true), true);
            foreach ($list as $k => $v)
            {
//                if ($v['astr_id'] === 11)
//                {

                foreach ($v as $k_item => $v_item)
                {
                    if (in_array($k_item, $keys_encode))
                    {
                        $list[$k][$k_item] = $this->encrypt_item($v_item, $k, $k_item);

                        $update = [];//更新内容
                        $update[$k_item] = Util::encryptWithOpenssl($v_item);

                        $result = Db::table('zlcr_astr_info')->where('id', $v['id'])->update($update);
                        if ($result)
                        {
                            $list[$k][$k_item] .= '-更新成功';
                        } else
                        {
                            $list[$k][$k_item] .= '-更新失败';
                        }
                    }
                }
//                }

            }
        }
        catch (\Exception $e)
        {
            $list = [];
            Log::write('把银行卡、身份证数据加密：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return show(200, '加密失败');
        }

        return show(200, '加密成功', $list);
    }

    /**
     * 头像信息重置
     * https://local-beta-wechat.goddessxzns.com/test/test_astrologer/testAvatar
     */
    private function testAvatar()
    {
        try
        {
            $list = Db::table('zlcr_astr_info')->column('left_pic_info', 'astr_id');

            foreach ($list as $astrId => $leftPicInfoItem)
            {
                try
                {

                    $leftPicInfo = Util::decryptWithOpenssl($leftPicInfoItem);
                    $leftPicInfo = \GuzzleHttp\json_decode($leftPicInfo, true);

                    $month = date('m', strtotime($leftPicInfo['birthday']));//19900906
                    $day = date('d', strtotime($leftPicInfo['birthday']));//19900906

                    $sign_index = Util::getSignIndex($month, $day);

                    $result = Db::table('zlcr_astr')->where('id', $astrId)->update(['avatar' => "/zhunle_astrologer/avatar/{$sign_index}.png"]);
                    CacheManage::getInstance()->setCacheConfig('astr_admin.astr', $astrId)->rmCache();
                    if ($result)
                    {
                        $list[$astrId] = [
                            'info' => $leftPicInfo,
                            'tip' => '更新成功',
                            'sign' => $sign_index
                        ];
                    } else
                    {
                        $list[$astrId] = [
                            'info' => $leftPicInfo,
                            'tip' => '更新失败',
                            'sign' => $sign_index
                        ];
                    }
                }
                catch (\Exception $e)
                {
                }
            }
        }
        catch (\Exception $e)
        {
            // $list = [];
            Log::write('获取身份证信息解密获取头像信息错误：' . $e->getMessage() . '占星师Id：' . ($astrId ?? 0) . '失败行数：' . $e->getLine(), 'error');
            return show(200, '更新头像失败', $list ?? []);
        }

        return show(200, '更新头像成功', $list);
    }


    /**
     * 加密测试
     * @param $pre_encode
     * @param $k
     * @param $k_item
     * @return string
     */
    private function encrypt_item($pre_encode, $k, $k_item)
    {
        $after_encode = Util::encryptWithOpenssl($pre_encode);
        $after_decode = Util::decryptWithOpenssl($after_encode);
//        Log::write('加密之前：' . $pre_encode, 'error');
//        Log::write('加密之后：' . $after_encode, 'error');
//        Log::write('解密之后：' . $after_decode);
        Log::write($k . '-' . $k_item . '是否相同：' . ($pre_encode == $after_decode ? '相同' : '不相同 '));

        if ($pre_encode == $after_decode)
        {
            return '相同';
        } else
        {
            return '不相同';
        }
        return $after_encode;
    }


}
